package com.zdj.algorithm;

/**
 * @author zdj
 * @date 2024-05-28 17:35
 * 二分查找
 */
public class BinarySearch {

    public static int search(int[] nums, int target) {
        int left = 0;
        int right = nums.length - 1;

        while (left <= right) {
//            int mid = (right + left ) / 2;
            int mid = (right - left) / 2 + left;
            if (nums[mid] == target) {
                return mid;
            } else if (nums[mid] > target) {
                right = mid - 1;
            } else {
                left = mid + 1;
            }
        }
        return -1;
    }

    /**
     * 获取x的平方根 结果只保留 整数部分
     */
    public static int mySqrt(int x) {
        int left = 0;
        int right = x;
        while (left <= right) {
            int mid = (right - left) / 2 + left;
            if (mid == 0) {
                return Math.max(mid, x);
            }
            if (x / mid == mid) {
                return mid;
            }
            if ((x / mid > mid) && (x / (mid + 1) < mid + 1)) {
                return mid;
            } else if (mid > x / mid) {
                right = mid - 1;
            } else {
                left = mid + 1;
            }
        }
        return 0;
    }

    public static void main(String[] args) {
        int[] nums = new int[]{-1, 0, 3, 5, 9, 12};
//        System.out.println(search(nums, 22));
        System.out.println(mySqrt(1));
    }
}
